package com.example.demo.service;

import com.example.demo.dao.UserMapper;
import com.example.demo.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;

@Service
public class UserService {
    @Autowired
    UserMapper userMapper;

    //测试使用，id查所有
    public User getUserInfo(String user_id) {
        return userMapper.selectUserById(user_id);
    }

    //登录验证，返回登录结果
    public int loginStatus(String user_telephone, String user_password) {
        User user = userMapper.selectUserByTel(user_telephone);
        if (user == null)
            return -1;//用户不存在
        else if (user.getUser_password().equals(user_password))
            return 0;//密码正确
        else
            return -2;//密码错误
    }

    //登录，返回user对象
    public User loginUser(String user_telephone) {
        return userMapper.selectUserByTel(user_telephone);
    }

    //注册
    public int register(String user_name, String user_password, String user_telephone, String user_address, String user_mailbox) {
        User user = userMapper.selectUserByTel(user_telephone);
        if (user != null)
            return -1;//用户已存在
        else {
            Timestamp register_time = new Timestamp(System.currentTimeMillis());
            String user_id = register_time.getTime() + "_" + user_telephone;//生成一个唯一id
            userMapper.insertUser(user_id, user_name, user_password, user_telephone, user_address, user_mailbox);
            return 0;//注册成功
        }
    }

    //修改用户信息
    public int modifyUser(String user_id, String user_name, String user_password,
                          String user_telephone, String user_address, String user_mailbox) {
        User user = userMapper.selectUserById(user_id);
        if (user == null)
            return -1;
        userMapper.updateUser(user_id, user_name, user_password, user_telephone, user_address, user_mailbox);
        return 0;
    }
}
